//
//  HealthScore.swift
//  Runner
//
//  Created by minhao on 2025/11/3.
//

import Foundation
import Flutter

class HealthScore{
    
    
    /// 获取健康评分
    
    func getHealthScore(result: @escaping FlutterResult) {
        // 获取各项得分
        let memoryScore = getMemoryScore()
        let storageScore = getStorageScore()
        let temperatureScore = getTemperatureScore()
        let securityScore = getSecurityScore()
        
        // 计算综合评分 (按照权重计算)
        let overallScore = memoryScore.score * 0.3 +
        storageScore.score * 0.25 +
        temperatureScore.score * 0.2 +
        securityScore.score * 0.25
        
        let healthData: [String: Any] = [
            "overallScore": overallScore,
            "memory": [
                "score": memoryScore.score,
                "totalMemory": memoryScore.totalMemory,
                "availableMemory": memoryScore.availableMemory,
                "usagePercentage": memoryScore.usagePercentage
            ],
            "storage": [
                "score": storageScore.score,
                "totalStorage": storageScore.totalStorage,
                "availableStorage": storageScore.availableStorage,
                "usagePercentage": storageScore.usagePercentage
            ],
            "temperature": [
                "score": temperatureScore.score,
                "temperature": temperatureScore.temperature,
                "status": temperatureScore.status
            ],
            "security": [
                "score": securityScore.score,
                "riskLevel": securityScore.riskLevel,
                "issues": securityScore.issues
            ]
        ]
        
        result(healthData)
    }
    
    // MARK: - 内存得分计算
    private struct MemoryScoreResult {
        let score: Double
        let totalMemory: Int
        let availableMemory: Int
        let usagePercentage: Double
    }
    
    private func getMemoryScore() -> MemoryScoreResult {
        // 获取内存信息 (这里使用模拟数据，实际项目中需要调用系统API)
        let totalMemory = 6 * 1024 * 1024 * 1024 // 6GB 模拟
        let availableMemory = 2 * 1024 * 1024 * 1024 // 2GB 可用模拟
        
        let usagePercentage = Double(totalMemory - availableMemory) / Double(totalMemory) * 100.0
        
        // 基于可用内存比例计算得分 (可用比例越高得分越高)
        let availableRatio = Double(availableMemory) / Double(totalMemory)
        let score = availableRatio * 100.0
        
        return MemoryScoreResult(
            score: min(score, 100.0),
            totalMemory: totalMemory,
            availableMemory: availableMemory,
            usagePercentage: usagePercentage
        )
    }
    
    // MARK: - 存储得分计算
    private struct StorageScoreResult {
        let score: Double
        let totalStorage: Int
        let availableStorage: Int
        let usagePercentage: Double
    }
    
    private func getStorageScore() -> StorageScoreResult {
        do {
            let fileSystemAttributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory())
            
            guard let totalSpace = fileSystemAttributes[.systemSize] as? NSNumber,
                  let freeSpace = fileSystemAttributes[.systemFreeSize] as? NSNumber else {
                return StorageScoreResult(score: 0, totalStorage: 0, availableStorage: 0, usagePercentage: 0)
            }
            
            let totalStorage = totalSpace.uint64Value
            let availableStorage = freeSpace.uint64Value
            
            let usagePercentage = Double(totalStorage - availableStorage) / Double(totalStorage) * 100.0
            
            // 基于可用存储比例计算得分
            let availableRatio = Double(availableStorage) / Double(totalStorage)
            let score = availableRatio * 100.0
            
            return StorageScoreResult(
                score: min(score, 100.0),
                totalStorage: Int(totalStorage),
                availableStorage: Int(availableStorage),
                usagePercentage: usagePercentage
            )
            
        } catch {
            return StorageScoreResult(score: 0, totalStorage: 0, availableStorage: 0, usagePercentage: 0)
        }
    }
    
    // MARK: - 温度得分计算
    private struct TemperatureScoreResult {
        let score: Double
        let temperature: Double
        let status: String
    }
    
    private func getTemperatureScore() -> TemperatureScoreResult {
        // 模拟温度数据 (实际项目中需要调用系统API获取温度)
        let simulatedTemperature = Double.random(in: 35.0...60.0)
        
        let score: Double
        let status: String
        
        if simulatedTemperature <= 45.0 {
            // 正常温度：35~45℃ -> 得分 100
            score = 100.0
            status = "normal"
        } else if simulatedTemperature <= 55.0 {
            // 偏高温度：46~55℃ -> 得分 70
            score = 70.0
            status = "high"
        } else {
            // 过高温度：>55℃ -> 得分 30
            score = 30.0
            status = "overheat"
        }
        
        return TemperatureScoreResult(
            score: score,
            temperature: simulatedTemperature,
            status: status
        )
    }
    
    // MARK: - 安全得分计算
    private struct SecurityScoreResult {
        let score: Double
        let riskLevel: String
        let issues: [String]
    }
    
    private func getSecurityScore() -> SecurityScoreResult {
        var issues: [String] = []
        var riskLevel = "none"
        
        // 检查越狱 (模拟检查)
        let isJailbroken = checkJailbreak()
        if isJailbroken {
            issues.append("设备可能已越狱")
            riskLevel = "high"
        }
        
        // 检查其他安全项目...
        // 例如：系统版本、应用签名、调试模式等
        
        let score: Double
        switch riskLevel {
        case "none":
            score = 100.0
        case "low":
            score = 70.0
        case "high":
            score = 30.0
        default:
            score = 100.0
        }
        
        return SecurityScoreResult(
            score: score,
            riskLevel: riskLevel,
            issues: issues
        )
    }
    
    /// 检查设备是否越狱 (基础检查)
    private func checkJailbreak() -> Bool {
        // 常见的越狱检查方法
        let jailbreakFilePaths = [
            "/Applications/Cydia.app",
            "/Library/MobileSubstrate/MobileSubstrate.dylib",
            "/bin/bash",
            "/usr/sbin/sshd",
            "/etc/apt"
        ]
        
        for path in jailbreakFilePaths {
            if FileManager.default.fileExists(atPath: path) {
                return true
            }
        }
        
        // 检查是否可以写入系统目录
        let stringToWrite = "Jailbreak Test"
        do {
            try stringToWrite.write(toFile: "/private/JailbreakTest.txt",
                                    atomically: true, encoding: .utf8)
            // 如果写入成功，说明设备可能越狱
            return true
        } catch {
            // 写入失败，设备正常
        }
        
        return false
    }
    
}
